package com.springboot.security.config;


import com.springboot.security.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: TongRui乀
 * @Date: 2019/1/24 13:47
 * @description：
 */
@Slf4j
@Component
public class TestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        log.info("登陆成功！");

        if(authentication instanceof UsernamePasswordAuthenticationToken){
            UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken)authentication;

            Object principal = token.getPrincipal();

            if(principal instanceof User){
                User loginUser = (User)principal;

                response.addCookie(new Cookie("loginUser", loginUser.getUserName()));
                response.sendRedirect("/system/index.html");
            }
        }

    }
}
